package com.fare.taluo.ftp;

import java.io.File;
import java.io.IOException;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.util.Assert;

import com.fare.taluo.ftp.channel.FTPChannel;
import com.fare.taluo.ftp.channel.SFTPChannel;

/**
 * FTP客户端，提供上传，下载等操作交互
 * <p>一般地，这里只是建立FTP连接后，调用{@link FTPChannel}类方法，完成业务应用
 * <br/>示例：new FTPClient("127.0.0.1").downRemoteFile("c:/ftp/test/test.txt");
 * <br/>返回值为一个枚举对象{@link DownloadStatus}或{@link UploadStatus}，业务应用可以根据该枚举上的描述{@link DownloadStatus#getDesc}给出用户提示
 * @author xiangsf 2012-12-6
 * @See com.csair.taluo.application.impl.ftp.FTPConnect
 * @See com.csair.taluo.application.impl.ftp.DownloadStatus
 * @See com.csair.taluo.application.impl.ftp.UploadStatus
 */
public class FTPClient {

	protected Logger logger = Logger.getLogger(getClass());
	private FtpConfiguration ftpConfig;
	
	public FTPClient(FtpConfiguration ftpConfig){
		Assert.notNull(ftpConfig, "ftp服务配置属性对象不可为空!");
		this.ftpConfig = ftpConfig;
	}
	
	public FTPClient(String ftpHost){
		Assert.hasText(ftpHost, "ftp服务主机ip地址不可为空！");
		try {
			this.ftpConfig = FtpConfigurationManager.getInstance().getFtpConfigurationWithIp(ftpHost);
		} catch (ConfigurationException e) {
			logger.error("根据服务主机IP获得配置出错!", e);
		}
		Assert.notNull(this.ftpConfig, String.format("获取服务主机IP为[%s]的FTP配置为空", ftpHost));
	}
	/**
	 * 下载远程文件到默认（ftp配置）目录下
	 * @param remoteFileName
	 * @return
	 * @throws IOException
	 */
	public DownloadStatus downRemoteFile(String remoteFileName) throws Exception{
		return this.downRemoteFile(remoteFileName, null);
	}
	/**
	 * 下载远程文件到指定目录下
	 * @param remoteFileName 远程文件全路径
	 * @param storeLocalDir 本地保存目录
	 * @return
	 * @throws IOException
	 */
	public DownloadStatus downRemoteFile(String remoteFileName, String storeLocalDir) throws Exception{
		FTPService ftp = null;
		try {
			if("sftp".equalsIgnoreCase(ftpConfig.getFtpType())){
				ftp = new SFTPChannel(ftpConfig);
			}else{
				ftp = new FTPChannel(ftpConfig).connect();
			}
			String realLocalDir = StringUtils.isNotEmpty(storeLocalDir) ? storeLocalDir : this.ftpConfig.getLocaldir();
			realLocalDir = realLocalDir.endsWith(File.separator) ?
									realLocalDir : realLocalDir+File.separator;
			return ftp.downloadFile(new String[]{remoteFileName}, realLocalDir);
		} finally{
			if(ftp != null) ftp.disconnect();
		}
	}
	/**
	 * 下载远程目录下的全部文件，不包括子目录及其下文件
	 * @param remoteDir 远程目录
	 * @param storeLocalDir
	 * @return
	 * @throws IOException
	 */
	public DownloadStatus downRemoteFileInDir(String remoteDir, String storeLocalDir) throws Exception{
		FTPService ftp = null;
		try {
			if("sftp".equalsIgnoreCase(ftpConfig.getFtpType())){
				ftp = new SFTPChannel(ftpConfig);
			}else{
				ftp = new FTPChannel(ftpConfig).connect();
			}
			return ftp.downloadFilesInDir(remoteDir, storeLocalDir);
		} finally{
			if(ftp != null) ftp.disconnect();
		}
	}
	/**
	 * 下载远程目录下的全部文件，不包括子目录及其下文件
	 * 下载的文件保存到默认配置的路径下
	 * @param remoteDir 远程目录
	 * @return DownloadStatus
	 * @throws IOException
	 */
	public DownloadStatus downRemoteFileInDir(String remoteDir) throws Exception{
		return downRemoteFileInDir(remoteDir , null);
	}

	/**
	 * 上传本地文件到FTP服务器指定远程路径下
	 * @param localFileName 本地文件全路径
	 * @param storeRemoteDir 保存的远程路径
	 * @return
	 * @throws IOException
	 */
	public UploadStatus uploadLocalFile(String localFileName, String storeRemoteDir) throws Exception{
		FTPService ftp = null;
		try {
			if("sftp".equalsIgnoreCase(ftpConfig.getFtpType())){
				ftp = new SFTPChannel(ftpConfig);
			}else{
				ftp = new FTPChannel(ftpConfig).connect();
			}
			return ftp.uploadFile(new String[]{localFileName}, storeRemoteDir);
		} finally{
			if(ftp != null) ftp.disconnect();
		}
	}
	/**
	 * 上传本地文件到FTP服务器默认（FTP配置文件）路径下
	 * @param localFileName
	 * @return
	 * @throws IOException
	 */
	public UploadStatus uploadLocalFile(String localFileName) throws Exception{
		return uploadLocalFile(localFileName, null);
	}
}
